{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Saving Model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 实验说明\n",
    "\n",
    "训练模型的保存和读取"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.preprocessing import StandardScaler, PolynomialFeatures\n",
    "from sklearn.pipeline import Pipeline\n",
    "from sklearn.metrics import accuracy_score\n",
    "import os\n",
    "from sklearn.externals import joblib"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Load Model...\n",
      "y_hat = \n",
      " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
      " 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2 2 1 2 1 2 1 2 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1\n",
      " 2 2 2 2 1 1 1 1 1 1 1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 2 1 2 2 1 2 2 2 2\n",
      " 2 2 1 1 2 2 2 2 1 2 1 2 1 2 2 1 1 2 2 2 2 2 1 1 2 2 2 1 2 2 2 1 2 2 2 1 2\n",
      " 2 1]\n",
      "accuracy = 80.667%\n"
     ]
    }
   ],
   "source": [
    "data = pd.read_csv('iris.data', header=None)\n",
    "x = data[[0, 1]]\n",
    "y = pd.Categorical(data[4]).codes\n",
    "if os.path.exists('iris.model'):\n",
    "    print('Load Model...')\n",
    "    lr = joblib.load('iris.model')\n",
    "else:\n",
    "    print('Train Model...')\n",
    "    lr = Pipeline([('sc', StandardScaler()),\n",
    "                   ('poly', PolynomialFeatures(degree=3)),\n",
    "                   ('clf', LogisticRegression()) ])\n",
    "    lr.fit(x, y.ravel())\n",
    "y_hat = lr.predict(x)\n",
    "joblib.dump(lr, 'iris.model')\n",
    "print('y_hat = \\n', y_hat)\n",
    "print('accuracy = %.3f%%' % (100*accuracy_score(y, y_hat)))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
